//
//  SubmitVC.m
//  DataStatistics
//
//  Created by Kang on 16/3/10.
//  Copyright © 2016年 YTYangK. All rights reserved.
//

#import "SubmitVC.h"
#import "isPhoneNumber.h"
@interface SubmitVC () <UITextFieldDelegate, UIAlertViewDelegate> {
    BOOL isSVCClick;
    UIToolbar* SVCtoolbar;
    UIButton* SVCbut;
    IBOutlet NSLayoutConstraint* V_nextView_H;
}
@property (strong, nonatomic) IBOutlet NSLayoutConstraint* V_password;

@end

@implementation SubmitVC

- (void)viewDidLoad
{
    [super viewDidLoad];

    [self updateUI];

    if (SYSTEM_VERSION_LESS_THAN_OR_EQUAL_TO_W_orH(SCREEN_HEIGHT, @"568.0")) {
        V_nextView_H.constant = 30;
        if (SCREEN_HEIGHT == 480) {
            _V_password.constant += 9;
            _okBtn.titleLabel.font = [UIFont systemFontOfSize:14.f];
        }
    }
}
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    _pasField.delegate = self;
    _nameField.delegate = self;
    _againPasField.delegate = self;
    [_pasField addTarget:self action:@selector(SVCtextLengthMethod:) forControlEvents:UIControlEventEditingChanged];
    [_againPasField addTarget:self action:@selector(SVCtextLengthMethod:) forControlEvents:UIControlEventEditingChanged];
}
- (void)viewDidDisappear:(BOOL)animated
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"UITextFieldTextDidChangeNotification" object:_nameField];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)updateUI
{
    UITapGestureRecognizer* tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(keyboardHide:)];
    tapGestureRecognizer.cancelsTouchesInView = YES;
    [self.view addGestureRecognizer:tapGestureRecognizer];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(SVCtextfiledEditChanged:) name:@"UITextFieldTextDidChangeNotification" object:_nameField];

    self.title = NSLocalizedString(@"SVCtitle", nil);
    _pasText.text = NSLocalizedString(@"SVCpasText", @"密码引导语");
    _nameText.text = NSLocalizedString(@"SVCnameText", @"昵称导语");
    [_pasField addYTYanKTextFielStyle1:_pasField withString:NSLocalizedString(@"SVCpasField", nil)];
    self.pasField.secureTextEntry = YES;
    [_nameField addYTYanKTextFielStyle1:_nameField withString:NSLocalizedString(@"SVCnameField", nil)];
    [_againPasField addYTYanKTextFielStyle1:_againPasField withString:NSLocalizedString(@"FPVCorigPas", nil)];
    self.againPasField.secureTextEntry = YES;
    [self addkeyboardRingBtn];
    self.okBtn.userInteractionEnabled = NO;
    [self.okBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    [self.okBtn setTitle:NSLocalizedString(@"SVCokbtn", nil) forState:UIControlStateNormal];
}
// 键盘－ 按钮
- (void)addkeyboardRingBtn
{
    SVCtoolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 30)];
    SVCtoolbar.backgroundColor = RGB(28, 28, 28, 1);
    [SVCtoolbar setBarStyle:UIBarStyleBlack];

    SVCbut = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - 32 - 20, 0, 34, 30)];
    [SVCbut setTitle:NSLocalizedString(@"SVCokbtn", nil) forState:UIControlStateNormal];
    SVCbut.titleLabel.font = [UIFont systemFontOfSize:14.f];
    [SVCbut addTarget:self action:@selector(okMethod:) forControlEvents:UIControlEventTouchDown];
    SVCbut.userInteractionEnabled = NO;
    [SVCbut setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];

    [SVCtoolbar addSubview:SVCbut];
    [self.nameField setInputAccessoryView:SVCtoolbar];
}
// 限制长度
- (void)SVCtextLengthMethod:(UITextField*)textField
{

    [self setSendViewBtnShow];
    if (textField == self.pasField) {
        if (textField.text.length > 12) {
            textField.text = [textField.text substringToIndex:12];
        }
    }
    else if (textField == self.againPasField) {
        if (textField.text.length > 12) {
            textField.text = [textField.text substringToIndex:12];
        }
    }
    else if (textField == self.nameField) {
        if (textField.text.length > 12) {
            textField.text = [textField.text substringToIndex:12];
        }
    }
}
/// 控制 发送按钮是否显示
- (void)setSendViewBtnShow
{
    if (self.pasField.text.length > 0 && self.nameField.text.length > 0 && self.againPasField.text.length > 0) {
        self.okBtn.userInteractionEnabled = YES;
        [self.okBtn setTitleColor:RGB(14, 118, 199, 1) forState:UIControlStateNormal];
        SVCbut.userInteractionEnabled = YES;
        [SVCbut setTitleColor:RGB(14, 118, 199, 1) forState:UIControlStateNormal];
    }
    else {
        self.okBtn.userInteractionEnabled = NO;
        [self.okBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
        SVCbut.userInteractionEnabled = NO;
        [SVCbut setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    }
}


- (void)keyboardHide:(UITapGestureRecognizer*)tap
{
    [self resignRespondersForText];
}
- (void)resignRespondersForText
{
    if (isSVCClick) {
        isSVCClick = NO;
        if (SYSTEM_VERSION_LESS_THAN_OR_EQUAL_TO_W_orH(SCREEN_HEIGHT, @"568.0")) {
            
            CGRect frame = self.view.frame;
            frame.origin.y = 64;
            POPBasicAnimation *basic = [POPBasicAnimation animationWithPropertyNamed:kPOPViewFrame];
            basic.toValue = [NSValue valueWithCGRect:frame];
            [self.view pop_addAnimation:basic forKey:@"viewAnimFrame"];
        }
      
        [self.view endEditing:YES];
    }
}
- (void)textFieldDidBeginEditing:(UITextField*)textField
{
    if (!isSVCClick) {
        isSVCClick = YES;
    }
    if (SYSTEM_VERSION_EQUAL_TO_W_orH(SCREEN_HEIGHT, @"480.0")) {
         CGRect newFrome = self.view.frame;
        if (textField == self.nameField) {
            newFrome.origin.y = (-textField.tag - 1.9) * textField.size.height;
        }
        else if (textField == self.pasField) {
            newFrome.origin.y = 30;
        }
        else if (textField == self.againPasField) {
            newFrome.origin.y = 30;
        }
        [UIView animateWithDuration:0.24 animations:^{
            [self.view setFrame:newFrome];
        }];
        
    }else if (SYSTEM_VERSION_EQUAL_TO_W_orH(SCREEN_HEIGHT, @"568.0")) {
        CGRect newFrome = self.view.frame;
        if (textField == self.nameField) {
          newFrome.origin.y = -2.1 * textField.size.height;
        }else if (textField == self.pasField) {
            newFrome.origin.y = 30;
        }else if (textField ==  self.againPasField) {
            newFrome.origin.y = -30;
        }
        [UIView animateWithDuration:0.24 animations:^{
            [self.view setFrame:newFrome];
        }];
    }
}
- (BOOL)textFieldShouldReturn:(UITextField*)textField
{
    if (textField == _pasField) {
        [_againPasField becomeFirstResponder];
    }
    else if (textField == _againPasField) {
        [_nameField becomeFirstResponder];
    }
    else {
        //   [self okMethod:_okBtn];
        [self resignRespondersForText];
    }
    return YES;
}

// 监控NickName中文输入方法(限制长度)
- (void)SVCtextfiledEditChanged:(NSNotification*)obj
{

    UITextField* textfield = (UITextField*)obj.object;
    NSString* toBeString = textfield.text;
    // 键盘输入模式
    NSString* lang = [[UITextInputMode currentInputMode] primaryLanguage];
    // 简体中文输入，包括简体拼音，健体五笔，简体手写
    if ([lang isEqualToString:@"zh-Hans"]) {
        UITextRange* selectedRange = [textfield markedTextRange];
        //获取高亮部分
        UITextPosition* position = [textfield positionFromPosition:selectedRange.start offset:0];
        // 没有高亮选择的字，则对已输入的文字进行字数统计和限制
        if (!position) {
            if (toBeString.length > 15) {
                // textfield.text = [toBeString substringFromIndex:10]; //如果超过十个重新清空内容，获取后面输入的内容。
                textfield.text = [toBeString substringToIndex:15];
            }
            else {
                // 有高亮选择的字符串，则暂不对文字进行统计和限制
            }
        }
        else {
            // 中文输入法以外的直接对其统计限制即可，不考虑其他语种情况
            if (toBeString.length > 12)
                textfield.text = [toBeString substringToIndex:12];
        }
    }
    else if ([lang isEqualToString:@"emoji"]) {
         textfield.text = [textfield.text removeEmoji];
    }
    else if ([lang isEqualToString:@"en-US"]) {
        if (toBeString.length > 12)
            textfield.text = [toBeString substringToIndex:12];
    }

    [self setSendViewBtnShow];
}

- (IBAction)okMethod:(UIButton*)sender
{

    // 注册
    [self resignRespondersForText];

    NSCharacterSet* whithNewChars = [NSCharacterSet whitespaceAndNewlineCharacterSet];
    NSString* iphonePas = [_pasField.text stringByTrimmingCharactersInSet:whithNewChars];
    NSString* useNmae = [_nameField.text stringByTrimmingCharactersInSet:whithNewChars];
    NSString* againPas = [_againPasField.text stringByTrimmingCharactersInSet:whithNewChars];

    if (iphonePas.length < 6 || againPas.length < 6) {
        [MBProgressHUD yty_showErrorWithTitle:nil detailsText:NSLocalizedString(@"Please enter 6-12 characters", nil) toView:nil];
    }else {
        if (![isPhoneNumber checkPasswordAndNum:iphonePas] && ![isPhoneNumber checkPasswordAndNum:againPas]) { //
            [MBProgressHUD yty_showErrorWithTitle:nil detailsText:NSLocalizedString(@"The password contains illegal characters", nil) toView:nil];
        }
        else {
            if ([iphonePas isEqualToString:againPas]) {
                NSDictionary* dic = @{ @"loginName" : _SVC_phoneNumber,
                                       @"zone" : _SVC_areaNam,
                                       @"nickName" : [useNmae stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
                                       @"verifyCode" : _SVC_SMSCode,
                                       @"password" : iphonePas };
                NSLog(@"----->%@", dic);
                
                if (SYSTEM_VERSION_EQUAL_TO_W_orH(SCREEN_HEIGHT, @"480.0")) {
                    [self resignRespondersForText];
                }
                else {
                    [self.view endEditing:YES];
                }
                
                [[NetRequestClss sharedNetRequestClss] requestWithUrl:@"userInfo/userRegister.asp" requestWithHeader:nil requestWithParameters:dic requestWithViewController:self requestWithApiID:@"userRegister.asp" isMethod:true isListLoaded:false result:^(id objs, int status, NSString* msg) {
                    NSLog(@"----->%@", msg);
                    int result = [[[objs objectForKey:@"body"] objectForKey:@"result"] intValue];
                        if (result == 0) { // 失败
                        //    [MBProgressHUD yty_showErrorWithTitle:nil detailsText:NSLocalizedString(@"", nil) toView:nil];
                        }
                        else if (result == 1) { //成功
                            // 返回登录页
                            [MBProgressHUD showSuccess:NSLocalizedString(@"SVCP5", nil)];
                            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                                [self.navigationController popToRootViewControllerAnimated:YES];
                            });
                        }
                        else if (result == 2) { //已注册
                            [MBProgressHUD yty_showErrorWithTitle:nil detailsText:NSLocalizedString(@"SVCP2", nil) toView:nil];
                        }
                        else {
                            // 错误
                            //[UtilToolsClss addViewController:self withTitleStr:NSLocalizedString(@"Tap", nil) withMessage:NSLocalizedString(@"SVCP3", nil)];
                        }
                }];
            }else {
                [MBProgressHUD yty_showErrorWithTitle:nil detailsText:NSLocalizedString(@"Passwords do not match", nil) toView:nil];
            }
        }
    }
    
   
}
@end
